package com.coin.config.swagger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.http.HttpMethod;
import springfox.documentation.builders.*;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.*;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.*;
import java.util.function.Predicate;

/**
 * @Auther: 李 力
 * @Date: 2025/5/24
 * @Description: com.coin.config.swagger
 * @version: 1.0
 */
@Configuration
@EnableSwagger2
public class SwaggerAutoConfiguration {

    @Autowired
    private SwaggerProperties swaggerProperties;

    @Bean
    public Docket docket() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                .paths(PathSelectors.any())
                .build();
        //针对安全的配置
        docket.securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
        return docket;
    }

    /*
     * api信息的简介
     * */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().contact(
                        new Contact(swaggerProperties.getName(), swaggerProperties.getUrl(), swaggerProperties.getEmail())
                )
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .version(swaggerProperties.getVersion())
                //团队信息
                .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
                .build();
    }

    /**
     * 安全的规则配置
     */
    private List<SecurityScheme> securitySchemes() {
        return Arrays.asList(new ApiKey("Authorization", "Authorization", "Authorization"));
    }

    /**
     * 安全的上下文
     */
    private List<SecurityContext> securityContexts() {
        return Collections.singletonList(new SecurityContext(
                Collections.singletonList(new SecurityReference("Authorization", new AuthorizationScope[]{new AuthorizationScope("global", "accessResource")})),
                PathSelectors.any(),
                new Predicate<HttpMethod>() {
                    @Override
                    public boolean test(HttpMethod httpMethod) {
                        return true;
                    }
                },
                new Predicate<OperationContext>() {
                    @Override
                    public boolean test(OperationContext operationContext) {
                        return true;
                    }
                }
        ));
    }
}
